/**
 * Copyright 2012 Fonfon.Fenceer
 * All rights reserved.
 * 
 * @project 
 * @author Fonfon.Fenceer
 * @version 1.0
 * @data 2012-3-9
 */
package com.guidecaptain.core.common;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

/**
 * 
 * 
 * @author fonfon
 */
public class CookieManager {

	private HttpServletRequest request;
	private HttpServletResponse response;
	
	public CookieManager(HttpServletRequest request, HttpServletResponse response) {
		this.request = request;
		this.response = response;
		response.setHeader("P3P", "CP=CAO PSA OUR");
	}
	
	public void addCookie(String cookieName, String cookieValue) {
		addCookie(cookieName, cookieValue, "");
	}
	
	public void addCookie(String cookieName, String cookieValue, String domain) {
		addCookie(cookieName, cookieValue, domain, "/");
	}
	
	public void addCookie(String cookieName, String cookieValue, String domain, String path) {
		addCookie(cookieName, cookieValue, domain, path, -1);
	}
	
	public void addCookie(String cookieName, String cookieValue, String domain, String path, int age) {
		Cookie cookie = new Cookie(cookieName, cookieValue);
		cookie.setPath(path);
//		此方法接收一个以秒为单位的整数;
//		该整数表示 cookie 的最大生存期;
//		负值表示当关闭浏览器时，该 cookie 将被清除;
//		0 表示必须立即清除该 cookie;
		cookie.setMaxAge(age);
		cookie.setDomain(domain);
		
		response.addCookie(cookie);
	}
	
	public String getCookieValue(String cookieName) {
		if (StringUtils.isBlank(cookieName)) return null;
		
		Cookie[] cookies = request.getCookies();
		
		String value = null;
		if (cookies != null && cookies.length > 0) {
			for (int i = 0; i < cookies.length; i++) {
				Cookie cookie = cookies[i];
				if (cookieName.equals(cookie.getName())) {
					value = cookie.getValue();
				}
			}
		}
		
		return value;
	}
	
	public void deleteCookie(String cookieName) {
		if (StringUtils.isBlank(cookieName)) return;
		addCookie(cookieName, null, "", "/", 0);
		
//		Cookie[] cookies = request.getCookies();
//		if (cookies != null && cookies.length > 0) {
//			for (int i = 0; i < cookies.length; i++) {
//				Cookie cookie = cookies[i];
//				cookie.setMaxAge(0);
//				cookie.setPath("/");
//			}
//		}
	}
	
	public void clear(){
        Cookie[] cookies = request.getCookies();
		if (cookies != null && cookies.length > 0) {
			for (int i = 0; i < cookies.length; i++) {
				deleteCookie(cookies[i].getName());
			}
		}
	}
}
